// Package controller 处理所有的 HTTP 请求
package controller

// auth_controller.go
// 注册，登录相关 handel func

import (
	"gforum/global"
	"gforum/model"
	"gforum/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Register(ctx *gin.Context) {
	var newUser model.User

	err := ctx.ShouldBindJSON(&newUser)
	if err != nil {
		utils.BadRequest(ctx, err, "Invalid input")
		return
	}

	hashedPwd, err := utils.HashPassword(newUser.Password)
	if err != nil {
		utils.InternalServerError(ctx, err, "Error hashing password")
		return
	}

	newUser.Password = hashedPwd

	token, err := utils.GenerateJWT(newUser.Username)
	if err != nil {
		utils.InternalServerError(ctx, err, "Error generating token")
		return
	}

	err = global.Db.Create(&newUser).Error
	if err != nil {
		utils.InternalServerError(ctx, err, "Error creating user")
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"token": token})
}

func Login(ctx *gin.Context) {
	var input struct {
		Username string `json:"username" `
		Password string `json:"password" `
	}

	err := ctx.ShouldBindJSON(&input)
	if err != nil {
		utils.BadRequest(ctx, err, "Invalid input")
		return
	}

	var user model.User

	err = global.Db.Where("username = ?", input.Username).First(&user).Error
	if err != nil {
		utils.InternalServerError(ctx, err, "Invalid username")
		return
	}

	if !utils.CheckPassword(input.Password, user.Password) {
		utils.Unauthorized(ctx, nil, "Invalid password")
		return
	}

	token, err := utils.GenerateJWT(user.Username)
	if err != nil {
		utils.InternalServerError(ctx, err, "Error generating token")
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"token": token})
}
